<template>
  <div class="login-container">
    <van-nav-bar
      title="登录页"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <van-form @submit="onSubmit">
      <van-field
        v-model="phone"
        name="mobile"
        label="电话"
        placeholder="请输入电话号码"
        required
        :rules="[
          { required: true, message: '请请输入正确电话号码' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不对',
          },
        ]"
      />
      <van-field
        v-model="possword"
        type="text"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        required
        :rules="[
          { required: true, message: '请输入正确验证码' },
          { pattern: /\d{6}/, message: '验证码格式不对' },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLoadaing"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { saveToken } from '../../utils/token.js'
import { userLogin } from './user.js'
export default {
  name: 'login',
  data () {
    return {
      phone: '',
      possword: '246810',
      isLoadaing: false
    }
  },
  methods: {
    //   1.values是一个对象
    //   2.key 是表单中输入元素的name属性
    //   3.表单校验通过之后 会触发的回调函数
    onSubmit (values) {
      console.log('submit', values)
      this.isLoadaing = true
      //   发送登录请求
      userLogin(values.mobile, values.code)
        .then((res) => {
          console.log(res)
          this.$toast.success('登录成功')

          // 登录成功后保存token
          saveToken(res.data.data)
          // 跳转首页
          this.$router.push({ path: '/home' })
        })
        .catch(() => {
          this.$toast.fail('账户或者验证码错误')
        })
        .then(() => {
          this.isLoadaing = false
        })
    }
  }
}
</script>

<style lang="less">
.login-container {
  .van-nav-bar__content {
    background-color: #0098fa;
    .van-nav-bar__text {
      color: #fff;
    }
    .van-icon-arrow-left {
      color: #fff;
    }
    .van-ellipsis {
      color: #fff;
    }
  }
}
</style>
